package DAO;

import Model.User;

import java.sql.*;

/**
 * @program: wsn_blog
 * @description
 * @author:王松年
 * @creat: 2021-07-11 12:15:29
 **/
public class UserDAO {
    //注册用户
    public static int register(User registerUser) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        try{
            connection = DBUtil.getConnection();
            String sql = "insert into user(username,password,nickname) values(?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,registerUser.getUsername());
            statement.setString(2,registerUser.getPassword());
            statement.setString(3,registerUser.getNickname());
            return statement.executeUpdate();
        }finally {
            DBUtil.close(connection,statement);
        }
    }

    //根据登录时传入的用户进行查询
    public static User selectByUser(User loginUser) throws SQLException {
        User user = null;
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from user where username=?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,loginUser.getUsername());
            resultSet = statement.executeQuery();
            if (resultSet.next()){
                user= new User();
                user.setUsername(resultSet.getString("username"));
                user.setId(resultSet.getInt("id"));
                user.setNickname(resultSet.getString("nickname"));
                user.setPassword(resultSet.getString("password"));
                user.setHead(resultSet.getString("head"));
            }
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return user;
    }
    //删除用户:删除用户时，用户一定是登录了，此时根据用户id进行删除
    public static boolean deleteById(int id) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        try{
            connection = DBUtil.getConnection();
            String sql = "delete from user where id <=> ?";
            statement=connection.prepareStatement(sql);
            statement.setInt(1,id);
            return statement.executeUpdate()==1;
        }finally {
            DBUtil.close(connection,statement);
        }
    }
}
